package cn.fl.project.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.lnkcomp.condition.PrjLnkCompCrLimQC;
import fl.spl.facade.lnkcomp.constant.PrjLnkCompRelInfoConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.service.IPrjLnkCompCrLimService;
import cn.fl.project.service.IPrjLnkCompService;
import cn.fl.project.vo.PrjLnkCompCrLimVO;
import cn.fl.project.vo.PrjLnkCompVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSONObject;

/**
 * @Description: 挂靠公司授信额度 控制层
 */
@Controller
@RequestMapping("/project/prjLnkCompCrLim")
public class PrjLnkCompCrLimController extends BaseController {

	/**
	 * prjLnkCompCrLimService 服务层BEAN
	 */
	@Autowired
	private IPrjLnkCompCrLimService prjLnkCompCrLimService;
	
	@Autowired
	private IPrjLnkCompService prjLnkCompService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String compId = request.getParameter("compId");//挂靠公司ID
		ModelAndView view = new ModelAndView("project/prjlnkcomp/projectLnkCompCrLimList");
		view.addObject("compId", compId);
		BaseLogUtils.newWebLogger("挂靠公司授信额度，跳转到列表页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}

	/**
	 * 到挂靠公司授信页面
	 */
	@RequestMapping(value = "/toModifyPrjLnkCompCrLimPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPrjLnkCompCrLimPage(HttpServletRequest request, HttpServletResponse response) {
		String crLimId = request.getParameter("crLimId");
		PrjLnkCompCrLimVO vo = this.prjLnkCompCrLimService.selectById(Long.valueOf(crLimId));
		PrjLnkCompVO prjLnkCompVO = this.prjLnkCompService.selectById(vo.getPrjLnkCompId());
		ModelAndView view = new ModelAndView("project/prjlnkcomp/prjLnkCompCrLimModifyPage");
		view.addObject("crLimit", vo);
		view.addObject("prjLnkCompNm",prjLnkCompVO.getLnkCompNm());
		view.addObject("currCrAmt", vo.getCrHisAmt());
		view.addObject("crAmt", vo.getCrAmt());
		view.addObject("crHisAmt", vo.getCrHisAmt());
		BaseLogUtils.newWebLogger("挂靠公司授信额度，跳转到授信页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}
	/**
	 * 到挂靠公司授信详情页面
	 */
	@RequestMapping(value = "/toDetailPrjLnkCompCrLimPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPrjLnkCompCrLimPage(HttpServletRequest request, HttpServletResponse response) {
		String crLimId = request.getParameter("crLimId");
		PrjLnkCompCrLimVO vo = this.prjLnkCompCrLimService.selectById(Long.valueOf(crLimId));
		ModelAndView view = new ModelAndView("project/prjlnkcomp/prjLnkCompCrLimDetailPage");
		view.addObject("crLimit", vo);
		view.addObject("currCrAmt", vo.getCrHisAmt());
		view.addObject("crAmt", vo.getCrAmt());
		BaseLogUtils.newWebLogger("挂靠公司授信额度，跳转到详情页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String createStDate = request.getParameter("createStDate");
		String createEndDate = request.getParameter("createEndDate");
		String crAmt = request.getParameter("crAmt");
		String  compId = request.getParameter("compId");//挂靠公司id
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjLnkCompCrLimQC qc = new PrjLnkCompCrLimQC();
		if (StringUtils.isNotEmpty(createStDate)) {
			qc.setCreateStDate(DateUtils.formatStringToDate(createStDate, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(createEndDate)) {
			qc.setCreateEndDate(DateUtils.formatStringToDate(createEndDate, DateUtils.YYYY_MM_DD));
		}
		if(StringUtils.isNotBlank(crAmt)){
			qc.setCrAmt(DecimalUtils.convertYuanToFen(Double.valueOf(crAmt)));
		}
		qc.setPrjLnkCompId(Long.valueOf(compId));
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);

		Pager pager = this.prjLnkCompCrLimService.searchListPage(page);
		List<PrjLnkCompCrLimVO> list = (List<PrjLnkCompCrLimVO>) pager.getResultList();
		ListPageVO<PrjLnkCompCrLimVO> listPage = new ListPageVO<PrjLnkCompCrLimVO>(list, pager.getTotalCount());
		BaseLogUtils.newWebLogger("获取挂靠公司变更主表数据详情").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
				.setWarning(false)
				.setKeys("listPage", JSON.toJSONString(listPage))
				.info();
		return listPage;
	}

	/**
	 * 删除数据
	 */ 
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjLnkCompCrLimService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}

		return result;
	}

	/**
	 * 得到一条挂靠公司授信额度记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.newWebLogger("获取挂靠公司授信额度,id为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return result;
		}
		
		try {
			PrjLnkCompCrLimVO vo = this.prjLnkCompCrLimService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.newWebLogger("获取挂靠公司授信额度数据不存在!").setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
						.setWarning(false)
						.setKeys("id", id)
						.warn(LogExceptionEnum.COMMON_CODE_0002);
			}
			result.setData(vo);
			BaseLogUtils.newWebLogger("获取挂靠公司授信额度详情").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setKeys("result", JSON.toJSONString(result))
					.info();
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("获取挂靠公司授信额度,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("获取挂靠公司授信额度,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

	/**
	 * 新增挂靠公司授信额度
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjLnkCompCrLimVO entity = null;
		String crLimitId = request.getParameter("id");
		Long id = null;
		try {
			entity = getPrjLnkCompCrLimParams(request);
			if(StringUtils.isNotBlank(crLimitId)){
				id = Long.valueOf(crLimitId);
				entity.setId(id);
				this.prjLnkCompCrLimService.modify(entity);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
			}else{
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				entity.setIsDel(BaseConstant.IS_YESNO_NO);
				id = this.prjLnkCompCrLimService.add(entity);
			}
			result.setData(id);
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setKeys("result", JSON.toJSONString(result))
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}

		return result;
	}

	/**
	 * 新增挂靠公司授信额度并发起流程
	 */
	@RequestMapping(value = "/addAndApply.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addAndApply(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjLnkCompCrLimVO entity = null;
		Long id = null;
		try {
			   entity = getPrjLnkCompCrLimParams(request);
				entity.setIsDel(PrjLnkCompRelInfoConstant.PRJ_LNk_COMP_CR_LIM_SAVE_STATUS);
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			 result = this.prjLnkCompCrLimService.addAndApply(entity);
			result.setData(id);
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度并发起流程").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setKeys("result", JSON.toJSONString(result))
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度并发起流程,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newWebLogger("新增挂靠公司授信额度并发起流程,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SQOT_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}

		return result;
	}

	private PrjLnkCompCrLimVO getPrjLnkCompCrLimParams(HttpServletRequest request)throws BaseException {
		PrjLnkCompCrLimVO crLimVO = new PrjLnkCompCrLimVO();
		String prjLnkCompId = request.getParameter("compId");
		String startDt = request.getParameter("startDt");
		String endDt = request.getParameter("endDt");
		String crHisAmt = request.getParameter("currCrAmt");
		String crAmt = request.getParameter("crAmt");
		String isLimit = request.getParameter("isLimit");//是否限制
		if(StringUtils.isBlank(startDt)){
			throw new BaseException(BaseExceptionConstant.COMMON_0001,"开始时间不能为空！");
		}
		if(StringUtils.isBlank(endDt)){
			throw new BaseException(BaseExceptionConstant.COMMON_0001,"结束时间不能为空！");
		}
		if(StringUtils.isBlank(crAmt)){
			throw new BaseException(BaseExceptionConstant.COMMON_0001,"敞口金额不能为空！");
		}
		if(StringUtils.isNotBlank(isLimit)){
			if(isLimit.equals("true")){
				crLimVO.setIsLimit(BaseConstant.IS_YESNO_YES);	
			}else{
				crLimVO.setIsLimit(BaseConstant.IS_YESNO_NO);
			}
		}else{
			crLimVO.setIsLimit(BaseConstant.IS_YESNO_NO);
		}
		crLimVO.setCrAmt(DecimalUtils.convertYuanToFen(Double.valueOf(crAmt)).longValue());
		crLimVO.setPrjLnkCompId(Long.valueOf(prjLnkCompId));
		crLimVO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		crLimVO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		crLimVO.setStartDt(DateUtils.formatStringToDate(startDt, DateUtils.YYYY_MM_DD));
		crLimVO.setEndDt(DateUtils.formatStringToDate(endDt, DateUtils.YYYY_MM_DD));
		crLimVO.setCrHisAmt(DecimalUtils.convertYuanToFen(Double.valueOf(crHisAmt)).longValue());
		if(crLimVO.getCrAmt().compareTo(crLimVO.getCrHisAmt())>0){
			//提升
			crLimVO.setCrAmtDir(PrjLnkCompRelInfoConstant.CODE_CR_AMT_DIR_UP);
		}else{
			//降低
			crLimVO.setCrAmtDir(PrjLnkCompRelInfoConstant.CODE_CR_AMT_DIR_DOWN);
		}
		crLimVO.setIsValid(BaseConstant.IS_YESNO_YES);
		crLimVO.setIsHis(BaseConstant.IS_YESNO_NO);
		return crLimVO;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		PrjLnkCompCrLimVO entity = null;
		try {
			entity = new PrjLnkCompCrLimVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjLnkCompCrLimService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}
		return result;
	}
}

